import { createApp } from 'vue'
import router from './router/router.js'
import store from './store'
import App from './App.vue'
import 'animate.css/animate.min.css'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import WebSocketPlugin from './plugins/websocket.js'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { VueNativeSock } from 'vue-native-websocket'
import axios from 'axios'

const app = createApp(App)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

axios.interceptors.request.use(
  (config) => {
    const token = sessionStorage.getItem('token')
    if (token) {
      // 如果token存在，则在请求头中携带token
      config.headers.Authorization = `${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
axios.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 如果返回401未授权，则跳转到登录页
          router.replace({
            path: '/login',
            query: { redirect: router.currentRoute.fullPath }
          })
          break
      }
    }
    return Promise.reject(error.response.data)
  }
)
// 设置全局组件
// app.component("Show",Show);
// 为app实例挂着路由对象
app.directive('focus', {
  mounted (el) {
    el.focus()
  }
})

app.use(WebSocketPlugin, { url: 'ws://localhost:8081/ws' })
app.use(VueNativeSock, 'ws://localhost:8081/ws', {
  reconnection: true,
  reconnectionAttempts: 5,
  reconnectionDelay: 3000
})
app.use(store)
app.use(router)
app.mount('#app')
app.use(ElementPlus)
